<?php
/*
 * Created on 20 mars 2009
 * Created by Ludovic Reenaers
 * lreenaers@hotmail.com
 */


 class TokenDAO extends DAO{
 	private $Bean;
 	
 	function getById($id){
		//return a Token with a given id
		try
		{
				$query="select * from token where id=$id;";
				$statement=$this->pdo->query($query);
				$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
				foreach($array_obj as $Bean){
					$this->Bean = new Token((int)$Bean->id);
					$this->Bean->setName($Bean->name);
				}
		}
		catch(Exception $e)	{throw $e;}
		
		return $this->Bean;
	}
	function remove($Bean){
		try{
			$query="delete from token where id=".$Bean->getId().";";
			$this->pdo->exec($query);
			$bool=true;	
		}catch(Exception $e)	{
			$bool=false;
			$this->pdo->rollBack();
			}
		return $bool;
			
	}
	function getByName($name){
		//return a Langue with a given abr
		try
		{
				$query="select * from token where name=$name;";
				$statement=$this->pdo->query($query);
				$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
				foreach($array_obj as $Bean){
					$this->Bean = $this->getById((int)$Bean->id);
				}
		}
		catch(Exception $e)	{
			throw $e;
		}
		
		return $this->Bean;
	}
	function update($Bean){
		//update a given Langue
		try{
			$query = "update token set name='".$Bean->getName()."' where id=".$Bean->getId().";";
			$this->pdo->exec($query);
			$bool=true;	
		}
		catch(Exception $e)	{
			$bool=false;
			$this->pdo->rollBack();
			}
		return $bool;
	}
	function add($name){
		// insert and return a new Langue
		try{
			$query="select * from token where name='$name';";
			$statement=$this->pdo->query($query);
			$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
			if(count($array_obj)>0){
				$this->Bean = $this->getById((int)$array_obj[0]->id);
			}else{
				$insertQuery = "insert into token (id,name) values (null,'$name');";
				$this->pdo->exec($insertQuery);
				$this->Bean = $this->getById((int)$this->pdo->lastInsertId());
			}
		}catch(Exception $e)	{
			throw $e;
		}
		return $this->Bean;
	}
	function All(){
		try
		{
				$BeanArray = array();
				$query="select * from token;";
				$statement=$this->pdo->query($query);
				$array_obj=$statement->fetchAll(PDO::FETCH_OBJ);
				foreach($array_obj as $Bean){
					$this->Bean = $this->getById((int)$Bean->id);
					array_push($BeanArray,$this->Bean);
				}
		}
		catch(Exception $e)	{
			throw $e;
		}
		
		return $BeanArray;
		
	}
 }
?>
